<?php

namespace Frieza\Modules\McnUser\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Doraemon\model\McnUser as mMcnUser;
use Doraemon\model\McnUserAccount as mMcnAccount;
use Doraemon\model\McnUserExtendInfo as mMcnUserExtendInfo;
use Doraemon\model\McnUserProfession;
use Doraemon\model\Member as mMember;
use Doraemon\service\McnUser as sMcnUser;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\pockets\excel\ReadExcel;
use Doraemon\service\Right\UserRightNew;
use Doraemon\tools\Area;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Collapse;
use Encore\Admin\Widgets\Table;
use Doraemon\model\Es\McnUser as esMcnUser;


class McnUserController extends Controller
{
    const LEVEl_ONE = 1;
    const LEVEl_TWO = 2;
    const LEVEl_ONE_TITLE = '商业合作用户备选池';
    const LEVEl_TWO_TITLE = '商业合作高阶用户';

    public static function getTitle($iType)
    {
        return $iType == 1 ? self::LEVEl_ONE_TITLE : self::LEVEl_TWO_TITLE;
    }

    /**
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $iType = $request->input("type", 1);

        $this->_getScript();
        Log::debug("params参数",$params);
        $search = $this->_getSearchFields($params);
        Log::debug("search参数",$search);
        $aList = sMcnUser::getList($page, $pageSize, $search);

        $gridModel = new pGridDataModel($aList['list'], $aList['total'], [
            'perPage' => $pageSize
        ]);

        $currentFilterParam['province_id'] = $params['province'];
        $currentFilterParam['house_place_province_id'] = $params['house_place_province_id'];
        $currentFilterParam['profession_id'] = $params['profession'];

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $search, $currentFilterParam, $iType) {

                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableExport();

                $grid->tools(function (Grid\Tools $tool) use($iType) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '上传数据', '', url('/admin/mcnUser/list/create?type=' . $iType)));
                });
                $grid->tools(function ($tools) use ($search) {
                    $export_url = http_build_query($search);
                    $url = url('/admin/mcnUser/list/export?' . $export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="' . $url . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a></div>';
                    $tools->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) use ($currentFilterParam) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($currentFilterParam) {
                        $filter->equal('uid', 'uid')->placeholder("请输入用户uid");

                        $top = Area::getLocation();

                        $filter->equal('province', '地区')->select($top)->load('city',
                            '/admin/position/area4name');
                        $citys = Area::getLocation($currentFilterParam['province_id']);
                        $all_city = [];
                        foreach (array_values($citys) as $val) {
                            $all_city[$val] = $val;
                        }
                        $filter->equal('city', '市/区')->select($all_city);


                        $filter->between('age', '年龄')->placeholder("不限");
                        $filter->between('fan_num', '粉丝数');
                        $allUserProfession = \Doraemon\service\McnUser::getOneLevelPro();
                        $filter->equal('profession', '行业')->select($allUserProfession)->load('user_profession',
                            '/admin/mcnUser/getprofession');
                        $allUserProfession = \Doraemon\service\McnUser::getUserPro($currentFilterParam['profession_id']);
                        $filter->equal('user_profession', '职业')->select($allUserProfession);
                        $filter->between('house_area', '房屋面积');
                        //$filter->between('business_coo_score', '商业合作等级总分');

                        $filter->equal('whether_commerce_cooper', '商业合作')->select([0 => "全部", 1 => '可以', 2 => '不可以']);


                        $filter->equal('special_family_member', '特殊家庭成员')->select(['孩子' => '孩子', '老人' => '老人', '宠物' => '宠物']);
                        $filter->equal('responsible_operation', '负责运营');


                        //$filter->equal('family_structure', '家庭结构')->select([0 => '全部', '独居人士' => '独居人士', '二人世界' => '二人世界', '有娃夫妻' => '有娃夫妻', '三世同堂' => '三世同堂', '多元家庭' => '多元家庭']);
                        $filter->equal('human_description', '人的形容');
                        $filter->equal('is_sign', '是否签约')->select([0 => "全部", 1 => '是', 2 => '否']);
                        $filter->equal('sort', '排序方式')->select(['0' => '默认', 'fan_num' => '按照粉丝数', 'carrying_capacity' => '按照带货能力分数', 'user_active' => '按照近7天活跃度分数']);


                    });

                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($currentFilterParam) {
                        $filter->equal('nick', '昵称')->placeholder("请输入昵称");

                        $top = Area::getLocation();
                        $filter->equal('house_place_province_id', '房屋所在地')->select($top)->load('house_place_city',
                            '/admin/position/area4name');
                        $citys = Area::getLocation($currentFilterParam['house_place_province_id']);
                        $all_city = [];
                        foreach (array_values($citys) as $val) {
                            $all_city[$val] = $val;
                        }
                        $filter->equal('house_place_city', '市/区')->select($all_city);


                        $filter->equal('sex', '性别')->select([0=>"全部",1 => '男', 2 => '女']);
                        $filter->between('praise_collection', '获赞收藏');
                        $filter->equal('creator_level', '创作者等级lv')->checkbox(['0' => 'lv0', '1' => 'lv1', '2' => 'lv2', '3' => 'lv3', '4' => 'lv4', '5' => 'lv5', '6' => 'lv6', '7' => 'lv7']);
                        $filter->equal('decoration_status', '装修状态')->select(['准备装修' => '准备装修', '不需要装修' => '不需要装修', '正在装修' => '正在装修', '未知' => '未知']);

                        $filter->equal('other_platforms', '其他平台')->select([0 => '全部', '抖音' => '抖音', '小红书' => '小红书', 'bilibili' => 'bilibili', '微博' => '微博', '住小帮' => '住小帮', '一兜糖' => '一兜糖', '逛逛' => '逛逛', '快手' => '快手', '知乎' => '知乎', '其他' => '其他']);


                        $filter->equal('community', '所在社群');
                        $filter->equal('love_category', '爱发品类');


                        $filter->equal('personal_preference', '个人偏好')->select([0 => '全部', '享受陪伴的爱宠一族' => '享受陪伴的爱宠一族', '经验丰富的装修能手' => '经验丰富的装修能手', '聪明能干的家务爱好者' => '聪明能干的家务爱好者', '会买会用的种草达人' => '会买会用的种草达人', '审美一流的搭配能手' => '审美一流的搭配能手', '先锋理性的测评达人' => '先锋理性的测评达人', '热爱自然的绿植达人' => '热爱自然的绿植达人', '品味独特的收藏爱好者' => '品味独特的收藏爱好者', '讲究吃喝的美食爱好者' => '讲究吃喝的美食爱好者', '教育有方的亲子家长' => '教育有方的亲子家长']);
                        $filter->equal('description_home', '家的形容-风格')->placeholder("家的形容");

                        $filter->equal('is_label', '是否打标签')->select([0 => "全部", 1 => '是', 2 => '否']);
                        $filter->equal('is_super', '是否为超级居住者')->select([0 => "全部", 1 => '是', 2 => '否']);

                        $filter->equal('order', '正序倒序')->select(['0' => '倒序', '1' => '正序']);


                    });

                    //商业信息筛选

                    //运营信息筛选

                    //标签筛选

                    $filter->expand();
                });


                $grid->column("avatar", "头像")->display(function () {
                    if (!empty($this->uid)) {
                        $fakeUrl = \Doraemon\service\Member::getAvatar($this->uid, 1, \Doraemon\tools\ImgUrl::IMAGE_SIZE_SQ_BIG);
                        return '<img src = "' . $fakeUrl . '" width = 45px height = 45px />';
                    } else {
                        return '';
                    }
                });
                $grid->column('uid', 'uid')->sortable();
                $grid->column('nick', '昵称');
                $grid->column('fan_num', '粉丝数');
                $grid->column('praise_collection', '获赞与收藏');
                $grid->column('area', '地区');
                $grid->column('level', '商业合作等级')->display(function(){
                    $level = \Doraemon\service\Right\UserRightNew::getUserLevelData($this->uid);
                    if ($level == UserRightNew::USER_LEVEL3) {
                        return '淘金新手';
                    } elseif (in_array($level, [UserRightNew::USER_LEVEL4, UserRightNew::USER_LEVEL5])) {
                        return '淘金达人';
                    } elseif (in_array($level, [UserRightNew::USER_LEVEL6, UserRightNew::USER_LEVEL7])) {
                        return '淘金专家';
                    } else {
                        return '等级较低';
                    }
                });

                $grid->column('lase_landing_time', '上一次登陆时间')->display(function () {
                    if (empty($this->lase_landing_time)) {
                        return '--';
                    } else {
                        return date("Y-m-d H:i:s", $this->lase_landing_time);
                    }

                });
                $grid->column('last_production_time', '上一次发布时间')->display(function () {
                    if (empty($this->last_production_time)) {
                        return '--';
                    } else {
                        return date("Y-m-d H:i:s", $this->last_production_time);
                    }
                });
                $grid->column('responsible_operation', '负责运营');
                $grid->column('homepage', '个人主页')->display(function () {

                    $url = Hhzurl::h5Person($this->uid);
                    return <<<HTML
<p style="font-size: 16px"><a class="h5_person" target="_blank"  href='$url'>个人主页</a></p>
HTML;
                });

                $grid->actions(function ($actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->append('<a target="_blank" href="/admin/mcnUser/detail/' . $actions->row->uid . '" class="fa fa-info-circle">详情</a>');
                });
                Admin::script($this->optionSubmit());
            });

        return $content
            ->header("mcn列表")
            ->description(' ')
            ->breadcrumb(['text' => 'MCN'])
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('信息完善')
            ->breadcrumb(
                ['text' => '信息完善']
            )
            ->body(self::editAction($request, $id));
    }

    /**
     * 修改页面
     */
    public function editAction($request, $iUid)
    {
        $aData = sMcnUser::getAllInfo($iUid);
        if (empty($aData)) {
            return '没有用户';
        }

        if (!empty($aData['phone_num'])) {
//            $aData['phone_num'] = PhoneCrypto::decrypt($aData['phone_num'], 'magic_mirror_decrypt_sms', PhoneCrypto::VERSIN);
        }

        $form = new Form($aData);
        $form->hidden('uid')->default($aData['uid']);
        $form->hidden('type')->default($aData['type']);

        $form->radio('sex', '性别')->options(['1' => '男', '2' => '女', '0' => '未知'])->default('0');
        $form->radio('is_to_order', '是否接私单')->options(['1' => '是', '2' => '否'])->default('2');
        $form->radio('is_auth', '是否入淘')->options(['1' => '是', '0' => '否'])->default('0');

        $form->text('profession', '本职职业')->setWidth(4, 2);
        $form->text('people_num', '人口数')->setWidth(4, 2);
        $form->text('pet', '宠物')->setWidth(4, 2);
        $form->text('child', '孩子')->setWidth(4, 2);;//->max(10);
        $form->text('area', '地域')->setWidth(4, 2);
        $form->text('address', '地址')->setWidth(4, 2);
        $form->textarea('kol_label', 'KOL标签')->setWidth(4, 2);
        $form->textarea('brand_use', '家中品牌')->setWidth(4, 2);

        $form->number('industry_influence', '行业影响力')->setWidth(4, 2);
        $form->number('cooperation_num', '合作次数')->setWidth(4, 2);
        $form->number('performance_capacity', '履约能力')->setWidth(4, 2);

        $form->number('redbook_fans', '小红书粉丝量')->setWidth(4, 2);
        $form->text('redbook_update', '小红书更新情况')->setWidth(4, 2);
        $form->text('redbook_price', '小红书价格')->setWidth(4, 2);
        $form->number('weibo_fans', '微博粉丝量')->setWidth(4, 2);
        $form->text('weibo_update', '微博更新情况')->setWidth(4, 2);
        $form->text('weibo_price', '微博价格')->setWidth(4, 2);
        $form->text('image_text_price', '一口价报价图文')->setWidth(4, 2);
        $form->text('video_one_minute_down_price', '一口价报价视频60s及以下')->setWidth(4, 2);
        $form->text('video_one_minute_up_price', '一口价报价视频60s以上')->setWidth(4, 2);
        $form->text('stroll_id', '逛逛id')->setWidth(4, 2);

        if ($aData['type'] == self::LEVEl_TWO) {
            $form->number('bus_dynamic_output', '商业动态产出能力')->setWidth(4, 2);
            $form->number('control_ability', '控场能力')->setWidth(4, 2);
            $form->number('express_ability', '表达能力')->setWidth(4, 2);

            $form->number('bus_video_output', '商业视频产出能力')->setWidth(4, 2);
            $form->number('bus_article_output', '商业文章产出能力')->setWidth(4, 2);
            $form->number('cooperation_match', '商业配合度')->setWidth(4, 2);
            $form->number('lens_expression', '镜头表现力')->setWidth(4, 2);


            $form->text('account_name', '帐户名称')->setWidth(4, 2);
            $form->text('bank_card_num', '银行卡号')->setWidth(4, 2);
            $form->text('open_bank', '开户行')->setWidth(4, 2);
            $form->text('phone_num', '手机号')->setWidth(4, 2);
            $form->text('id_number', '身份证号')->setWidth(4, 2);
        }
        $form->textarea('remark', '备注	')->setWidth(4, 2);
        $form->action('/admin/mcnUser/list/save');
        return $form;
    }

    /**
     * 编辑提交信息
     */
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $iUid = $request['uid'];
        $iType = $request['type'];
        $aExtData = $aAccount = [];

        $aData = [
            'people_num' => $request['people_num'],
            'pet' => $request['pet'],
            'child' => $request['child'],
            'sex' => $request['sex'],
            'area' => $request['area'],
            'address' => $request['address'],
            'brand_use' => $request['brand_use'],
            'is_auth' => $request['is_auth'],
            'profession' => $request['profession'],
        ];

        $aExtData = [
            'industry_influence' => $request['industry_influence'],
            'kol_label' => $request['kol_label'],
            'cooperation_num' => $request['cooperation_num'],
            'is_to_order' => $request['is_to_order'],
            'remark' => $request['remark'],

            'performance_capacity' => $request['performance_capacity'],
            'redbook_fans' => $request['redbook_fans'],
            'redbook_update' => $request['redbook_update'],
            'redbook_price' => $request['redbook_price'],
            'weibo_fans' => $request['weibo_fans'],
            'weibo_update' => $request['weibo_update'],
            'weibo_price' => $request['weibo_price'],
            'image_text_price' => $request['image_text_price'],
            'video_one_minute_down_price' => $request['video_one_minute_down_price'],
            'video_one_minute_up_price' => $request['video_one_minute_up_price'],
            'stroll_id' => $request['stroll_id'],
        ];

        if ($iType == self::LEVEl_TWO) {
            $aExtData['bus_dynamic_output'] = $request['bus_dynamic_output'];
            $aExtData['control_ability'] = $request['control_ability'];
            $aExtData['express_ability'] = $request['express_ability'];
            $aExtData['bus_video_output'] = $request['bus_video_output'];
            $aExtData['bus_article_output'] = $request['bus_article_output'];
            $aExtData['cooperation_match'] = $request['cooperation_match'];
            $aExtData['lens_expression'] = $request['lens_expression'];

            $aAccount = [
                'account_name' => $request['account_name'],
                'bank_card_num' => $request['bank_card_num'],
                'open_bank' => $request['open_bank'],
                'phone_num' => PhoneCrypto::encrypt($request['phone_num'], PhoneCrypto::CLIENT_YAPI, PhoneCrypto::VERSIN),
                'id_number' => $request['id_number'],
            ];
        }

        $aExtendInfo = mMcnUserExtendInfo::getInfo(['uid' => $iUid]);
        $aAccountInfo = mMcnAccount::getInfo(['uid' => $iUid]);

        try {
            mMcnAccount::action(function () use ($iUid, $aData, $aExtData, $aAccount, $aAccountInfo, $aExtendInfo) {
                mMcnUser::updateByUid($iUid, $aData);
                if (!empty($aExtendInfo)) {
                    mMcnUserExtendInfo::updateByUid($iUid, $aExtData);
                } else {
                    $aExtData['uid'] = $iUid;
                    mMcnUserExtendInfo::add($aExtData);
                }
                if (!empty($aAccountInfo)) {
                    mMcnAccount::updateByUid($iUid, $aAccount);
                } else {
                    $aAccount['uid'] = $iUid;
                    mMcnAccount::add($aAccount);
                }
            });
            $sMsg = 'success';
            return redirect('admin/mcnUser/list?type=' . $iType)->with(compact($sMsg));

        } catch (\Exception $exception) {
            $msg = $exception->getMessage();
            return back()->with(compact($msg));
        }
    }

    public function add(Request $request, Content $content)
    {
        $request = $request->all();
        $iType = $request['type'];
        $sTitle = self::getTitle($iType);

        return $content
            ->header($sTitle . '-上传信息')
            ->breadcrumb(
                ['text' => '上传信息']
            )
            ->body(self::addAction($request, $iType));
    }

    public function addAction($request, $iType)
    {
        $tab = new Tab();
        $tab->add('上传数据', $this->uploadDataTab($iType));
        return $tab->render();
    }

    /**
     * 导出数据
     */
    public function export(Request $request)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);


        $search = $this->_getSearchFields($params);

        $aList = sMcnUser::getList($page, $pageSize, $search);

        if ($aList['total'] == 0) {
            $error = new MessageBag([
                'title' => '没有数据',
            ]);
            return back()->with(compact('error'));
        }

        //限制导出的总条数
        if($aList['total'] >=1000){
            $aList['total'] = 1000;
        }

        $pageTotal = ceil($aList['total']/$pageSize);
        $page++;
        $list = $aList['list'];
        while($page <= $pageTotal){
            $aList = sMcnUser::getList($page, $pageSize, $search);
            $list = array_merge($list,$aList['list']);
            $page++;
        }

        sMcnUser::export($list);
    }

    /**
     * 对账信息
     */
    public function account($iUid)
    {
        $aData = mMcnAccount::getInfo(['uid' => $iUid]);

        if (!empty($aData)) {
            $aData['title'] = '';
            $aData['data'] = [
                ['name' => '账户名称', 'value' => $aData['account_name']],
                ['name' => '银行卡号码', 'value' => $aData['bank_card_num']],
                ['name' => '开户行', 'value' => $aData['open_bank']],
//                ['name' => '手机号', 'value' => PhoneCrypto::decrypt($aData['phone_num'], 'magic_mirror_decrypt_sms', PhoneCrypto::VERSIN)],
                ['name' => '手机号', 'value' => ''], // 目前得到的信息是这个页面下掉了。 所以先这么处理
                ['name' => '身份证号', 'value' => $aData['id_number']],
            ];
            $res = $this->boxTest($aData['data'], $aData['title']);
        } else {
            $res = '暂无信息';
        }
        echo $res;
    }

    /**
     * 上传数据
     */
    public function uploadDataTab()
    {
        $form = new Form();
        $form->html("<span style='color:red;'>上传数据会覆盖老数据</span>");
        $form->file('excel', '上传Excel')->required()->removable()->help('请严格按照模板格式');
        $form->action("/admin/mcnUser/list/uploadData");
        $form->html('<div class="btn-group pull-left">
                <a class="btn btn-info pull-right" href= "/admin/mcnUser/download/DataTemplate" target="_blank">模板下载</a>
            </div>');
        $form->disableReset();
        return $form->render();
    }

    /**
     * 下载信息模版
     * @deprecated 文件上传到服务器了。
     */
    public function downloadDataTemplate(){

        $re = file_get_contents("https://static.haohaozhu.cn/assets/docs/mcn/mcn_import_v3.xlsx");

        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=mcn_import_v3.xlsx");
        header("Content-Transfer-Encoding:binary");
        echo $re;exit;

    }

    /**
     * 上传数据
     */
    public function uploadData(Request $request)
    {
        ini_set('memory_limit', '100M');

        $allData = $request->all();
        $file = $allData["excel"];

        $newFile = 'mcnUser-' . date('YmdHis') . '.xlsx';
        $newFilePath = '/tmp' . '/' . $newFile;
        $rs = move_uploaded_file($file, $newFilePath);
        if (!$rs) {
            $error = new MessageBag([
                'title' => '文件保存失败',
            ]);
            return back()->with(compact('error'));
        }
        $excel = new ReadExcel($newFile);
        $excelRawData = $excel->getExcelDataNoHeader($newFilePath);
//        echo "<pre>";
//        print_r($excelRawData);exit;
        try {

            foreach ($excelRawData as $row => $itemArr) {
                $iUid = intval(trim($itemArr[0]));

                if ($row <= 0 || empty($iUid)) {
                    continue;
                }

                Log::debug('mcn上传数据调试1', $itemArr);


                $mcnUser = $this->_getMcnUser($itemArr);
                $aMcnUserExtends = $this->_getMcnUserExtends($itemArr);

                Log::debug('mcn上传数据调试2', $aMcnUserExtends);

                //基本信息
                $aInfo = mMcnUser::getInfo(['uid' => $iUid]);
                if (!empty($aInfo)) {
                    mMcnUser::updateByUid($iUid, $mcnUser);
                } else {
                    $mcnUser['uid'] = $iUid;
                    mMcnUser::add($mcnUser);
                }
                //扩展信息
                if (!empty($aMcnUserExtends['user_profession'])) {
                    $aProfession = McnUserProfession::get('*', ['name' => $aMcnUserExtends['user_profession']]);
                    if (empty($aProfession)) {
                        $aProfession = McnUserProfession::get('*', ['name' => '其他']);
                    }
                    if ($aProfession) {
                        $aMcnUserExtends['user_profession'] = $aProfession['id'];
                    } else {
                        unset($aMcnUserExtends['user_profession']);
                    }
                }

                $aExtend = mMcnUserExtendInfo::getInfo(['uid' => $iUid]);
                if (!empty($aExtend)) {
                    mMcnUserExtendInfo::updateByUid($iUid, $aMcnUserExtends);
                } else {
                    $aMcnUserExtends['uid'] = $iUid;
                    mMcnUserExtendInfo::add($aMcnUserExtends);
                }

                //es信息
                $esData = $this->_getEsData($itemArr);
                $esData['uid'] = $iUid;
                Log::debug('es 参数',$esData);
                if(!empty($esData)){
                    if (!empty($esData['user_profession'])) {
                        $aProfession = McnUserProfession::get('*', ['name' => $esData['user_profession']]);
                        if (empty($aProfession)) {
                            $esData['user_profession'] = '其他';
                        }
                    }
                   
                    $client = new esMcnUser();
                    $res = $client->saveData((string)$iUid, $esData);
                    Log::debug('es结果',[$res]);
                }

            }

            $success = new MessageBag([
                'title' => '批量导入完成',
            ]);
            return back()->with(compact('success'));

        } catch (\PHPExcel_Reader_Exception $exception) {
            $error = new MessageBag([
                'title' => 'Excel文件读取失败，只支持xls格式',
                'info'=>$exception->getMessage(),
            ]);
            return back()->with(compact('error'));
        } catch (\Throwable $exception){
            $error = new MessageBag([
                'title' => '导入失败',
                'info'=>$exception->getMessage(),
            ]);
            Log::error("import error ",[$exception->getMessage(),$exception->getTraceAsString()]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 详情展示
     */
    public function detail($iUid = 0)
    {
        return Admin::content(
            function (Content $content) use ($iUid) {

                $aUser = mMember::getUser($iUid);
                $aData = sMcnUser::getAllInfo($iUid);
                //用户头像
                $fakeUrl = \Doraemon\service\Member::getAvatar($iUid, 1, \Doraemon\tools\ImgUrl::IMAGE_SIZE_SQ_BIG);
                $aData['base_title'] = '用户基础信息';
                //获取孩子性别
                if ($aData['sex'] == 0) {
                    $sSex = '未知';
                } elseif ($aData['sex'] == 1) {
                    $sSex = '男孩';
                } else {
                    $sSex = '女孩';
                }
                //带货标签
                $sGoodsLabel = '';
                if (!empty($aData['commerce_goods_label'])) {
                    $aGoodsLabel = explode('|', $aData['commerce_goods_label']);
                    foreach ($aGoodsLabel as $val) {
                        $sGoodsLabel .= $val . "<br/>";
                    }

                }
                $aData['base'] = [
                    ['name' => '用户头像', 'value' => '<img src = "' . $fakeUrl . '" width = 45px height = 45px />'],
                    ['name' => '用户昵称', 'value' => $aData['nick']],
                    ['name' => '用户Uid', 'value' => $aData['uid']],
                    ['name' => '用户职业', 'value' => $aData['profession']],
                    ['name' => '是否是设计师', 'value' => $aData['is_designer'] == 1 ? '是' : '否'],
                    ['', ''],
                    ['name' => '人口数', 'value' => $aData['people_num']],
                    ['name' => '宠物', 'value' => $aData['pet']],
                    ['name' => '孩子', 'value' => $aData['child']],
                    ['name' => '性别', 'value' => $sSex],
                    ['name' => '地域', 'value' => $aData['area']],
                    ['name' => '地址', 'value' => $aData['address']],
                    ['name' => '房屋风格', 'value' => $aData['house_style']],
                    ['name' => '房屋面积', 'value' => $aData['house_area']],
                    ['name' => '房屋格局', 'value' => $aData['house_pattern']],
                ];
                $aData['info_title'] = '信息';
                $aData['info'] = [
                    ['name' => '站内粉丝数', 'value' => $aData['fan_num'], 'column' => '精选动态占比', 'column_value' => $aData['choiceness_dynamic_ratio'],],
                    ['name' => '粉丝粘性', 'value' => $aData['fan_viscosity'], 'column' => '精选短视频占比', 'column_value' => $aData['choiceness_video_ratio'],],
                    ['name' => '动态总数量', 'value' => $aData['dynamic_total_num'], 'column' => '精选动态数量', 'column_value' => $aData['choiceness_dynamic_total_num'],],
                    ['name' => '动态近30天曝光量', 'value' => $aData['dynamic_exposure'], 'column' => '动态近30天交互量', 'column_value' => $aData['dynamic_interactive_total_num'],],
                    ['name' => '行业影响力', 'value' => $aData['industry_influence'], 'column' => 'KOL标签', 'column_value' => $aData['kol_label'],],
                    ['', '', '', ''],
                    ['name' => '<span style="color:red">商业用户等级</span>', 'value' => '<span style="color:red">' . $aData['level'] . '</span>', 'column' => '履约能力', 'column_value' => $aData['performance_capacity']],
                    ['name' => '合作次数', 'value' => $aData['cooperation_num'], 'column' => '生产等级', 'column_value' => $aData['user_production_level']],
                    ['name' => '是否接私单', 'value' => $aData['is_to_order'] == 1 ? '是' : '否', 'column' => '生产标签', 'column_value' => $aData['production_label']],
                    ['name' => '用户活跃', 'value' => $aData['user_active'], 'column' => '家用有的品牌', 'column_value' => $aData['brand_use']],
                    ['name' => '带货能力', 'value' => $aData['carrying_capacity'], 'column' => '带货商品标签', 'column_value' => $sGoodsLabel],
                    ['', '', '', ''],
                ];
                $aData['info_ext'] = [
                    ['name' => '商业配合度', 'value' => $aData['cooperation_match']],
                    ['name' => '商业动态产出能力', 'value' => $aData['bus_dynamic_output']],
                    ['name' => '商业视频产出能力', 'value' => $aData['bus_video_output']],
                    ['name' => '商业文章产出能力', 'value' => $aData['bus_article_output']],
                    ['name' => '控场能力', 'value' => $aData['control_ability']],
                    ['name' => '镜头表现力', 'value' => $aData['lens_expression']],
                    ['name' => '表达能力', 'value' => $aData['express_ability']],
                    ['', '', 'name' => '', 'value' => '<a class="btn button-success" href="javascript:layer.open({type: 2,title: \'对账信息\',maxmin: true,area: [\'400px\', \'400px\'],content: \'/admin/mcnUser/list/account/' . $iUid . '\'});"><i class="fa fa-folder-open-o"/> 对账信息</a>'],
                ];

                if ($aData['type'] == self::LEVEl_TWO) {
                    $aData['info'] = array_merge($aData['info'], $aData['info_ext']);
                }

                $aData['other_title'] = '其他平台信息';
                $aData['other'] = [
                    ['name' => '小红书粉丝量', 'value' => $aData['redbook_fans']],
                    ['name' => '小红书更新情况', 'value' => $aData['redbook_update']],
                    ['name' => '小红书价格', 'value' => $aData['redbook_price']],
                    ['name' => '', 'value' => ''],
                    ['name' => '微博粉丝量', 'value' => $aData['weibo_fans']],
                    ['name' => '微博更新情况', 'value' => $aData['weibo_update']],
                    ['name' => '微博价格', 'value' => $aData['weibo_price']],
                    ['name' => '', 'value' => ''],
                    ['name' => '逛逛ID', 'value' => $aData['stroll_id']],
                    ['name' => '逛逛一口价：', 'value' => ''],
                    ['name' => '图文', 'value' => $aData['image_text_price']],
                    ['name' => '视频60s及以下', 'value' => $aData['video_one_minute_down_price']],
                    ['name' => '视频60s以上', 'value' => $aData['video_one_minute_up_price']],
                    ['name' => '', 'value' => ''],
                    ['name' => '备注', 'value' => $aData['remark']],
                ];

                $sTitle = self::getTitle($aData['type']);
                $content->header($sTitle . '用户信息详情');

                $content->row(
                    function (Row $row) use ($aData) {
                        $row->column(3, function (Column $column) use ($aData) {
                            $column->append($this->boxTest($aData['base'], $aData['base_title']));
                        });
                        $row->column(6, function (Column $column) use ($aData) {
                            $column->append($this->boxTest($aData['info'], $aData['info_title']));
                        });
                        $row->column(3, function (Column $column) use ($aData) {
                            $column->append($this->boxTest($aData['other'], $aData['other_title']));
                        });

                    }
                );
            }
        );
        return $row->render();
    }

    public function boxTest($aInfo, $sTitle)
    {
        $box = new Box();
//        $box->collapsable();
//        $box->style('info');
        $box->solid();
        $box->title($sTitle);
        $box->content($this->table($aInfo));
        return $box;
    }

    public function table($aInfo)
    {
        $table = new Table([], $aInfo);
        return $table->render();
    }

    public function collapseTest($title, $aData)
    {
        $collapse = new Collapse();
        $collapse->add($title, '');
        $collapse->add('点击查看对账信息', $this->table($aData));
        return $collapse->render();
    }

    /**
     * 徽章展示
     */
    public function optionSubmit()
    {
        return <<<SCRIPT
            $('.all_emblem').on('click',function(){
                var uid = $(this).data('uid');
                layer.open({
                    type: 2,
                    title: '用户全部徽章',
                    maxmin: true,
                    area: ['800px', '600px'],
                    content:'/admin/user/AllEmblem/'+uid,
                });
            });
SCRIPT;
    }


    public function getProfession(Request $request)
    {
        $pid = $request->input('q', 0);
        $pro = \Doraemon\service\McnUser::getUserPro($pid);
        $format = array_map(function ($k, $v) {
            return [
                'id'   => $v,
                'text' => $v,
            ];
        }, array_keys($pro), $pro);
        return response()->json($format);
    }


    private function _getScript()
    {
        Admin::script(
            <<<EOF
$('input[type=radio][name=select_area]').on('ifChecked',function(){
    if(this.value == 1) {
        $("select.multiplearea").parent().parent().hide();
        $("select.province").parent().parent().show();
        $("select.city").parent().parent().show();
    }else {
        $("select.multiplearea").parent().parent().show();
        $("select.city").parent().parent().hide();
        $("select.province").parent().parent().hide();
    }
});
$('input[type=radio][name=select_area]:checked').trigger('ifChecked');
EOF
        );
    }


    private function _getMcnUser($itemArr)
    {

        //是否入淘
        if (trim($itemArr[11]) == '是') {
            $itemArr[11] = 1;
        } else {
            $itemArr[11] = 0;
        }


        $aMcnUser = [
            'profession' => 1,
            'is_auth' => 11,
        ];

        $_aMcnUser = [];
        foreach ($aMcnUser as $key => $value) {
            empty($itemArr[$value]) ? "" :$_aMcnUser[$key] = $itemArr[$value];
        }

        return $_aMcnUser;
    }

    private function _getMcnUserExtends($itemArr)
    {

        $_aMcnUserExtends = [];
        $platformArr = [
            'douyin' => [ 'nick' =>15,'fans_num'=>16, 'home_page_links' => 17],
            'xiao_hong_shu' => ['nick' =>18,'fans_num'=>19, 'home_page_links' => 20],
            'bilibili' => ['nick' =>21,'fans_num'=>22, 'home_page_links' => 23],
            'weibo' => ['nick' =>24,'fans_num'=>25, 'home_page_links' => 26],
            'zhu_xiao_bang' => ['nick' =>27,'fans_num'=>28, 'home_page_links' => 29],
            'yi_dou_tang' => ['nick' =>30,'fans_num'=>31, 'home_page_links' => 32],
            'guang_guang' => ['nick' =>33,'fans_num'=>34, 'home_page_links' => 35],
            'kuai_shou' => ['nick' =>36,'fans_num'=>37, 'home_page_links' => 38],
            'zhihu' => ['nick' =>39,'fans_num'=>40, 'home_page_links' => 41],
            'other_platform' => ['nick' =>42,'fans_num'=>43, 'home_page_links' => 44],
        ];

        foreach ($platformArr as $key => $plat) {
            $_plat = [];
            foreach($plat as $field => $pos){
                if(!empty($itemArr[$pos])){
                    $_plat[$field]= $itemArr[$pos];
                }
            }

            if(!empty($_plat)){
                $_aMcnUserExtends[$key] = json_encode($_plat, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            }

        }
        list($_human,$_home) = $this->_getMultiFields($itemArr);
        if(!empty($_human)){
            $_aMcnUserExtends['human_description'] = json_encode($_human, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        if(!empty($_home)){
            $_aMcnUserExtends['description_home'] = json_encode($_home, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }

        $aMcnUserExtends = [
            'user_profession' => 1,
            'postal_address' => 2,
            'performance_capacity' => 3,
            'whether_commerce_cooper' => 4,
            'fans_love_watch' => 5,
            'industry_influence' => 6,
            'bus_article_output' => 7,
            'bus_video_output' => 8,
            'express_ability' => 9,
            'cooperation_match' => 10,
            'responsible_operation' => 12,
            'community' => 13,
            'operational_remarks' => 14,
            'personal_preference' => 45,
            'is_label' => 57,
            'is_sign' => 58,
            'share_proportion' => 59,
            'guang_guang_img_text_price' => 60,
            'guang_guang_60s_video_price' => 61,
            'guang_guang_60s_120s_video_price' => 62,
            'red_book_img_text_price' => 63,
            'red_book_video_price' => 64,
            'is_super' => 65,
        ];


        foreach ($aMcnUserExtends as $key => $value) {
            empty($itemArr[$value]) ? "" : $_aMcnUserExtends[$key] = $itemArr[$value];
        }

        if (!empty($_aMcnUserExtends['is_label'])) {
            $_aMcnUserExtends['is_label'] = ['是' => 1, '否' => 2][$_aMcnUserExtends['is_label']];
            if (empty($_aMcnUserExtends['is_label'])) {
                Log::error('is_label数据不合法', $itemArr[$aMcnUserExtends['is_label']]);
                unset($_aMcnUserExtends['is_label']);
            }
        }
        if (!empty($_aMcnUserExtends['is_sign'])) {
            $_aMcnUserExtends['is_sign'] = ['是' => 1, '否' => 2][$_aMcnUserExtends['is_sign']];
            if (empty($_aMcnUserExtends['is_sign'])) {
                Log::error('is_label数据不合法', $itemArr[$aMcnUserExtends['is_sign']]);
                unset($_aMcnUserExtends['is_sign']);
            }
        }
        if (!empty($_aMcnUserExtends['is_super'])) {
            $_aMcnUserExtends['is_super'] = ['是' => 1, '否' => 2][$_aMcnUserExtends['is_super']];
            if (empty($_aMcnUserExtends['is_super'])) {
                Log::error('is_super数据不合法', $itemArr[$aMcnUserExtends['is_super']]);
                unset($_aMcnUserExtends['is_super']);
            }
        }
        if (!empty($_aMcnUserExtends['whether_commerce_cooper'])) {
            $_aMcnUserExtends['whether_commerce_cooper'] = ['是' => 1, '否' => 2][$_aMcnUserExtends['whether_commerce_cooper']];
            if (empty($_aMcnUserExtends['whether_commerce_cooper'])) {
                Log::error('whether_commerce_cooper数据不合法', $itemArr[$aMcnUserExtends['whether_commerce_cooper']]);
                unset($_aMcnUserExtends['whether_commerce_cooper']);
            }
        }

        return $_aMcnUserExtends;

    }


    private function _getSearchFields($params){
        $search = [];
        $searchFields = [
            //具体
            'sex',
            'user_profession',
            'whether_commerce_cooper',
            'other_platforms',
            'love_category',
            'family_structure',
            'personal_preference',
            'is_sign',
            'is_label',
            'is_super',
            //范围
            'age',
            'fan_num',
            'praise_collection',
            'house_area',
            'business_coo_score',
            //多个
            'uid',
            'nick',
            'province',
            'city',
            'house_place_province_id',
            'house_place_city',
            'level',
            'creator_level',
            'decoration_status',
            'special_family_member',
            'responsible_operation',
            'community',
            'human_description',
            'description_home',
            //排序
            'sort',
            'order',
            'page',
            'per_page'
        ];

        foreach($searchFields as $field){
            if(isset($params[$field]) && !empty($params[$field])){
                $search[$field] = $params[$field];
            }
        }

        return $search;
    }


    private function _getEsData($itemArr){

        list($_human,$_home) = $this->_getMultiFields($itemArr);

        $_aEsData = [];

        if(!empty($_human)){
            $_aEsData['human_description'] = json_encode($_human, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        if(!empty($_home)){
            $_aEsData['description_home'] = json_encode($_home, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }

        $aEsData = [
            'uid'=>0,
            'user_profession' => 1,//
            'area' => 2,
            'whether_commerce_cooper' => 4,
            'responsible_operation' => 12,
            'community' => 13,
            'personal_preference' => 45,
            'family_structure'=>46,
            'is_super' => 65,
            'is_label' => 57,
            'is_sign' => 58,
        ];


        foreach ($aEsData as $key => $value) {
            empty($itemArr[$value]) ? "" : $_aEsData[$key] = $itemArr[$value];
        }

        if (!empty($_aEsData['is_label'])) {
            $_aEsData['is_label'] = ['是' => 1, '否' => 2][$_aEsData['is_label']];
            if (empty($_aEsData['is_label'])) {
                Log::error('is_label数据不合法', $itemArr[$aEsData['is_label']]);
                unset($_aEsData['is_label']);
            }
        }
        if (!empty($_aEsData['is_sign'])) {
            $_aEsData['is_sign'] = ['是' => 1, '否' => 2][$_aEsData['is_sign']];
            if (empty($_aEsData['is_sign'])) {
                Log::error('is_label数据不合法', $itemArr[$aEsData['is_sign']]);
                unset($_aEsData['is_sign']);
            }
        }
        if (!empty($_aEsData['is_super'])) {
            $_aEsData['is_super'] = ['是' => 1, '否' => 2][$_aEsData['is_super']];
            if (empty($_aEsData['is_super'])) {
                Log::error('is_super数据不合法', $itemArr[$aEsData['is_super']]);
                unset($_aEsData['is_super']);
            }
        }
        if (!empty($_aEsData['whether_commerce_cooper'])) {
            $_aEsData['whether_commerce_cooper'] = ['是' => 1, '否' => 2][$_aEsData['whether_commerce_cooper']];
            if (empty($_aEsData['whether_commerce_cooper'])) {
                Log::error('whether_commerce_cooper数据不合法', $itemArr[$aEsData['whether_commerce_cooper']]);
                unset($_aEsData['whether_commerce_cooper']);
            }
        }
        
        if(!empty($_aEsData)){
            $_aEsData['status'] = 1;
        }

        return $_aEsData;
    }


    private function _getMultiFields($itemArr){

        $human_description = [
            "family_structure" => 46,
            "member_of_family" => 47,
            "consumer_preferences" => 48,
            "personal_temperamen" => 49,
            "life_preference" => 50
        ];
        $_human = [];
        foreach($human_description as $field => $pos){

            if(!empty($itemArr[$pos])){
                $_human[$field] = $itemArr[$pos];
            }
        }

        $home = [
            "targeted_design" => 51,
            "functional_area" => 52,
            "home_temperament" => 53,
            "initial_state_of_house" => 54,
            "style" => 55,
            "special_design" => 56
        ];

        $_home = [];
        foreach ($home as $field => $pos){

            if(!empty($itemArr[$pos])){
                $_home[$field] = $itemArr[$pos];
            }
        }

        return [$_human,$_home];
    }
}